<template>
    <div class="wrapper">
        <top-header title="砍价"></top-header>
        <div class="body">
            <div class="content">
                <image class="content_img" v-if="carDetail.headImg" :src="carDetail.headImg"></image>
                <image class="content_img" v-else src="bmlocal://assets/acw/car.jpg"></image>
                <div>
                    <text class="content_first">{{carDetail.pAllname}}</text>
                    <div class="content_two">
                        <text class="content_two1">{{carDetail.pYear}}年</text>
                        <text class="content_two2">{{carDetail.pKilometre}}万公里</text>
                        <text class="content_two1">{{carDetail.p1}}</text>
                    </div>
                    <div class="content_third">
                        <text class="content_third_price">{{carDetail.pPrice}}万</text>
                        <WxcButton @wxcButtonClicked="createdOrder(carDetail)" class="content_four_share" type="blue" size="medium" text="立即购买"></WxcButton>
                    </div>
                </div>
            </div>
            <list class="bargain_list">
                <cell class="middle_border"></cell>
                <cell class="cell_cont">
                    <div class="bargain_progress">
                        <div class="bargain_num">
                            <text class="bargain_num1" v-if="bargainTotal.bargainPrice">已砍价 ￥{{parseFloat(bargainTotal.bargainPrice * 10000).toFixed(2)}}</text>
                            <!--<text class="bargain_num1" v-else>已砍价 ￥0</text>-->
                            <!--<text class="bargain_num2" v-if="bargainTotal.bargainPrice < 1">还可以砍价 ￥{{10000 - (bargainTotal.bargainPrice * 10000)}}</text>-->
                            <!--<text class="bargain_num2" v-else-if="bargainTotal.bargainPrice >= 1">还差 ￥0</text>-->
                            <!--<text class="bargain_num2" v-else>还差 ￥10000</text>-->
                        </div>
                        <wxc-progress class="progress" :value="(bargainTotal.bargainPrice/1)*100"
                            bar-color='#1E90FF'
                            :bar-height=16
                            :bar-radius=16
                            :bar-width=640></wxc-progress>
                    </div>
                    <div class="share">
                        <text class="share_text" @click="bargainSelf" v-if="isBargained == 0">自己砍价</text>
                        <text class="share_text" v-else @click="shareWX">分享给好友，多砍一刀</text>
                    </div>
                </cell>
                <cell class="middle_border"></cell>
                <cell class="cell_cont" v-if="bargainList.length != 0">
                    <div class="bargainlist1">
                        <text class="bargain_rule">砍价列表</text>
                        <text class="bargain_num2">{{bargainTotal.bargainCount}}人帮砍</text>
                    </div>
                    
                    <div class="bargain_list_content" v-if="barginListShow" v-for="item in bargainList">
                        <text class="list_content1" v-if="item.fromUid == item.toUid">自己砍价已砍掉</text>
                        <text class="list_content1" v-else>{{item.toUname}}</text>
                        <text class="list_content2">  ￥{{parseFloat(item.bargainPrice * 10000).toFixed(2)}}</text>
                    </div>
                </cell>
                <cell class="middle_border"></cell>
                <cell class="cell_cont">
                    <text class="bargain_rule">砍价规则</text>
                    <div class="rule_content">
                        <text class="rule_content_word">1、砍价活动每7天推出三辆，活动周期1个月</text>
                        <text class="rule_content_word">2、砍价抢车成功用户7个工作日内提车（如有变动另行通知）</text>
                        <text class="rule_content_word">3、车辆运输费用及购置税由用户承担</text>
                        <text class="rule_content_word">4、每个新注册用户只能砍价一次。</text>
                        <text class="rule_content_word">5、砍价没有上限，砍价车辆以交付定金为成交依据</text>
                        <text class="rule_content_word">6、抢车成功用户15个工作日内没有提车视为放弃购买（因厂家原因除外）</text>
                        <text class="rule_content_word">7、活动最终解释权归添美商务管理有限公司</text>
                    </div>
                </cell>
            </list>
        </div>
        <div class="order_pop" v-if="payPopShow">
            <text class="order_pop_title">订单信息</text>
            <div class="order_pop_content">
                <text class="order_pop_text1">订单编号：</text>
                <text class="order_pop_text2">{{order.orderId}}</text>
            </div>
            <div class="order_pop_content">
                <text class="order_pop_text1">车主：</text>
                <text class="order_pop_text2">{{order.name}}</text>
            </div>
            <div class="order_pop_content">
                <text class="order_pop_text1">价格：</text>
                <text class="order_pop_text2">{{order.price}}万元</text>
            </div>
            <div class="order_pop_content">
                <text class="order_pop_text1">优惠：</text>
                <text class="order_pop_text2">{{order.offer}}万元</text>
            </div>
             <div class="order_pop_content">
                <text class="order_pop_text1">实际价格：</text>
                <text class="order_pop_text2">{{order.pay}}万元</text>
            </div>
            <div class="order_pop_content">
                <text class="order_pop_text1">订金：</text>
                <text class="order_pop_text2">{{order.realpay}}元</text>
            </div>
            <!-- <div class="order_pop_content">
                <text class="order_pop_text1">保证金：</text>
                <text class="order_pop_text2">{{order.p10}}万元</text>
            </div> -->
            <!--<div class="order_pop_content">-->
                <!--<text class="order_pop_text1">看车地点：</text>-->
                <!--<text class="order_pop_text2">{{order.address}}</text>-->
            <!--</div>-->
            <div class="order_pop_button">
                <text class="order_pop_cencel" @click="cancel">取消</text>
                <text class="order_pop_pay" @click="payOrder(order)">支付</text>
            </div>
        </div>
    </div>
</template>
<script>
import { WxcButton, WxcProgress } from 'weex-ui';
var bmWXShare = weex.requireModule('bmWXShare')
var bmWXPay = weex.requireModule('bmWXPay')
bmWXPay.initWX('wxf4cc61d23f1c0461')
// bmWXPay.initWX('wxb41ad58cf1f362f9')
import header from '../common/header'
export default {
    components: { WxcButton, WxcProgress,
        'top-header': header,
    },
    data () {
        return {
            token: '',
            carId: '',
            userId: '',
            bargainTotal: '',
            bargainList: [],
            carDetail: '',
            isBargained: 0,
            barginListShow: false,
            payPopShow: false,
            order: {
                orderId: '',
                name: '',
                price: '',
                offer: '',
                pay: '',
                realPay: '',
                address: '',
            },
        }
    },
    created () {
        let user = this.$storage.getSync('UserInfo')
        this.userId = user.id
        this.$router.getParams().then(resData => {
            console.log(resData)
            this.carId = resData.carId
            this.getCarById(resData.carId)
        })
        this.wxInit();
    },
    methods: {
        // 返回
        back () {
            this.$router.back();
        },
        // 自己砍价
        bargainSelf () {
            this.getBargainCarList({
                from_uid: this.userId,
                car_id: this.carId
            })
        },
        // 自己砍价接口
        getBargainCarList (param) {
            this.$fetch({
                method: 'POST',    // 大写
                name: 'bargain.addBargainBySelf', //当前是在apis中配置的别名，你也可以直接绝对路径请求 如：url:http://xx.xx.com/xxx/xxx
                data: param
            }).then(resData => {
                // 成功回调
                console.log(resData)
                if(resData && resData.errno == 0){
                    this.getBargainDetailList({
                        uid: this.userId,
                        car_id: this.carId,
                        page: 1,
                        limit: 10,
                        sort: 'id',
                        order: 'asc'
                    })
                } else {
                    this.$notice.toast({ message: resData.errmsg})
                }
            }, error => {
                // 错误回调
                console.log(error)
            })
        },
        // 好友砍价排行
        getBargainDetailList (param) {
            this.$fetch({
                method: 'POST',    // 大写
                name: 'bargain.bargainDetailListByUid', //当前是在apis中配置的别名，你也可以直接绝对路径请求 如：url:http://xx.xx.com/xxx/xxx
                data: param
            }).then(resData => {
                // 成功回调
                console.log(resData)
                if(resData && resData.errno == 0){
                    this.bargainTotal = resData.data.bargainEntity
                    this.isBargained = resData.data.alreadyBargainBySelf
                    this.bargainList = resData.data.bargainDetailEntityList
                    this.barginListShow = true
                } else {
                    this.$notice.toast({ message: resData.errmsg})
                }
            }, error => {
                // 错误回调
                console.log(error)
            })
        },
        // 查询汽车详情
        getCarById (id) {
            this.$fetch({
                method: 'POST',    // 大写
                name: 'cars.getCarById', //当前是在apis中配置的别名，你也可以直接绝对路径请求 如：url:http://xx.xx.com/xxx/xxx
                data: {
                    car_id: id
                }
            }).then(resData => {
                // 成功回调
                console.log(resData)
                if(resData && resData.errno == 0){
                    this.carDetail = resData.data.car
                    this.carDetail.headImg = resData.data.car.pPics.split(';')[1]
                } else {
                }
                this.getBargainDetailList({
                    uid: this.userId,
                    car_id: id,
                    page: 1,
                    limit: 10,
                    sort: 'id',
                    order: 'asc'
                })
            }, error => {
                // 错误回调
                console.log(error)
            })
        },
        wxInit() {
            // 5cadf0fb0cafb25c0c00015c ios ||  5c655bf7b465f546ee00069e android
            if(weex.config.env.osName =='android'){
                bmWXShare.initUM('5c655bf7b465f546ee00069e')  
            } else {
                bmWXShare.initUM('5cadf0fb0cafb25c0c00015c')
            }
            bmWXShare.initWX({
                appKey: 'wxf4cc61d23f1c0461', // 微信开发平台申请的appkey
                appSecret: '155fabcaddd64ab33b83e6d7924b5a0e', // appKey对应的appSecret，
                redirectURL: '/js/pages/login/index.js' // 授权回调页面
            })
        },
        shareWX() {
            const vm = this;

            var result = bmWXShare.isInstallWXApp()

            if(!result) {
                this.$notice.toast({ message: "请先安装微信客户端！"})
                return;
            }
            var url = 'https://www.tl2c.cn'
            // var url = 'https://www.tl2c.com'
            bmWXShare.share({
                title:'好友喊你来砍价', // 分享的标题
                content:'小主，好友喊你来砍价，下载添美爱车APP即可获得一年2万公里质保兑换券，还有机会获得一年两次免费划痕修复兑换券。', // 分享的文字内容
                url: url + '/app/share?userId=' + this.userId + '&carId=' + this.carId, // 分享对应的URL地址，如h5、音乐链接、视频链接、小程序的链接
                // url: 'https://www.zosto.net/app/share', // 分享对应的URL地址，如h5、音乐链接、视频链接、小程序的链接
                image: url + '/app/storage/fetch/app_logo.png', // 分享的图片url
                // url: 'https://www.gh-cms.com/app/share', // 分享对应的URL地址，如h5、音乐链接、视频链接、小程序的链接
                // image: 'https://www.gh-cms.com/logo.png', // 分享的图片url
                // path: '', // 分享小程序用到的页面路径
                // userName: '' // 小程序名称
                shareType: 'Webpage', // 分享的类型
                platform: 'WechatSession' // 分享平台 朋友圈/好友（注意：历史版本的字段名是platforms,现在是一个字符串而不是数组）
            },function(resData){ // 注意： 历史版本返回的是一个promise对象，现在的是callback回调     
                // 成功回调
                console.log(":::::::::::::::::::::::::::::::Sucess");
                console.log(resData);
                vm.$notice.toast({ message: "分享成功"})
            },function(resData){
                // 失败回调
                console.log(":::::::::::::::::::::::::::::::Failer");
                console.log(resData);
                vm.$notice.toast({ message: "分享失败"})
            })
        },
        // 取消订单
        cancel () {
            this.payPopShow = false;
            this.order = {
                orderId: '',
                name: '',
                price: '',
                offer: '',
                pay: '',
                realPay: '',
                address: '',
            }
        },
        // 支付
        payOrder (order) {
            console.log(":::::::::::::::::2 " + JSON.stringify(order))
            console.log(":::::::::::::::::2 " + JSON.stringify(order.realpay))
            this.payPopShow = false;
            this.getPreOrderInfo({
                'orderId': order.orderId,
                'amount': order.realpay
            })
        },
        // 下单
        createdOrder (car) {
            var userInfo = this.$storage.getSync('UserInfo');
            let param = {
                "actual_amount": car.pPrice - this.bargainTotal.bargainPrice, 
                "address": car.lookcaradd, 
                "car_id": car.pId, 
                "city": car.lookcaradd, 
                "county": car.cid, 
                "description": car.pDetails, 
                "discount": this.bargainTotal.bargainPrice, 
                "mobile": car.pTel, 
                "order_type": car.selltype, 
                "orginal_amount": car.pPrice, 
                "province": car.lookcaradd, 
                "username": car.pUsername
            }
            this.order = {
                name: car.pUsername,
                price: car.pPrice,
                offer: this.bargainTotal.bargainPrice,
                pay: car.pPrice - this.bargainTotal.bargainPrice,
                address: car.lookcaradd,
            }
            this.token = userInfo.token;
            this.$fetch({
                method: 'POST',    // 大写
                name: 'order.add', //当前是在apis中配置的别名，你也可以直接绝对路径请求 如：url:http://xx.xx.com/xxx/xxx
                data: param,
                header: {
                    'X-TMACW-APP-Token': this.token
                }
            }).then(resData => {
                console.log(":::::::::::::::::" + JSON.stringify(resData))
                const vm = this;
                // 成功回调
                if(resData && resData.errno == 0) {
                    this.order.orderId = resData.data.orderId;
                    this.order.realpay = parseFloat(car.pPrice * (Number(car.p10) / 100) * 10000).toFixed(2),
                    console.log(":::::::::::::::::1 " + this.order.realpay)
                    this.payPopShow = true;
                } else {
                    this.$notice.toast({ message: resData.errmsg})
                }
            }, error => {
                // 错误回调
                this.$notice.toast({ message: "获取订单失败, 请重试"})
            })
        },
        getPreOrderInfo(param) {
            const vm = this;
            var result = bmWXPay.isInstallWXApp();
            
            if(!result) {
                this.$notice.toast({ message: "请先安装微信客户端！"})
                return;
            }
            console.log(":::::::::::::::::3 " + JSON.stringify(param))
            var userInfo = this.$storage.getSync('UserInfo');
            this.token = userInfo.token;
            this.$fetch({
                method: 'POST',    // 大写
                name: 'pay.pay', //当前是在apis中配置的别名，你也可以直接绝对路径请求 如：url:http://xx.xx.com/xxx/xxx
                data: param,
                header: {
                    'X-TMACW-APP-Token': this.token
                }
            }).then(resData => {
                
                // 成功回调
                if(resData && resData.errno == 0) {
                    // this.infoObj = resData.data.worker;
                    // var result = bmWXPay.isInstallWXApp()

                    var payId = resData.data.prepayId;

                    bmWXPay.pay({
                        // 微信支付所需必要参数
                        appid:resData.data.appId,
                        sign:resData.data.sign,
                        timestamp:resData.data.timeStamp,
                        noncestr:resData.data.nonceStr,
                        partnerid:resData.data.partnerId,
                        prepayid:resData.data.prepayId,
                        packageValue:resData.data.packageValue
                    },function(resData){
                        //   {"resCode":-2,"status":-2}__LOG
                        if(resData && resData.status == 0){
                            // vm.getPayStatus(payId);
                            vm.$notice.toast({ message: "支付成功"})
                        } else if (resData.status == -1) {
                            vm.$notice.toast({ message: "普通错误类型"})
                        } else if (resData.status == -2) {
                            vm.$notice.toast({ message: "您点击了取消或返回"})
                        } else if (resData.status == -3) {
                            vm.$notice.toast({ message: "发送失败"})
                        } else if (resData.status == -4) {
                            vm.$notice.toast({ message: "授权失败"})
                        } else if (resData.status == -5) {
                            vm.$notice.toast({ message: "微信不支持"})
                        } else {
                            vm.$notice.toast({ message: "失败，请重试"})
                        }
                        
                        // 支付结果
                        // resDate.status 说明
                        // 0,   /**< 成功    */
                        // -1,   /**< 普通错误类型    */
                        // -2,   /**< 用户点击取消并返回    */
                        // -3,   /**< 发送失败    */
                        // -4,   /**< 授权失败    */
                        // -5,   /**< 微信不支持    */
                    })
                } else {
                    this.$notice.toast({ message: resData.errmsg})
                }
            }, error => {
                // 错误回调
                this.$notice.toast({ message: "获取订单失败, 请重试"})
            })
        },
    }
}
</script>
<style>
.iconfont {
    font-family: iconfont;
}
.wrapper{
    background-color: #fff;
}
.body{
    padding-right: 20px;
    padding-left: 20px;
    justify-content: center;
}
.content{
    flex-direction: row;
    padding-top: 30px;
    padding-bottom: 30px;
    background-color: #fff;
}
.content_first{
    width: 480px;
    color: #666;
    font-size: 30px;
    margin-bottom: 10px;
}
.content_img{
    height: 240px;
    width: 200px;
    margin-right: 10px;
}
.content_two{
    flex-direction: row;
    margin-top: 20px;
    margin-bottom: 30px;
}
.content_third{
    flex-direction: row;
    justify-content: space-between;
    width: 450px;
    align-items: center;
}
.content_two1{
    color: #666;
    font-size: 30px;
    padding-left: 20px;
    padding-right: 20px;
}
.content_two2{
    color: #666;
    font-size: 30px;
    padding-left: 20px;
    padding-right: 20px;
    border-left-style: solid;
    border-left-width: 2px;
    border-left-color: #666;
    border-right-style: solid;
    border-right-width: 2px;
    border-right-color: #666;
}
.content_third_price{
    font-size: 40px;
    color: #ff2d2d;
    margin-left: 20px;
    margin-right: 40px;
}
.bargain_rule{
    /* background-color: #ffa240; */
    border-radius: 5px;
    height: 80px;
    line-height: 80px;
    text-align: left;
    color: #1E90FF;
}
.rule_content{
    background-color: #fff;
    padding-left: 20px;
    padding-right: 20px;
    padding-top: 40px;
    padding-bottom: 40px;
}
.rule_content_word {
    color: #666;
    margin-bottom: 8px;
}
.bargain_per{
    background-color: #ff2d2d;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    height: 80px;
}
.bargain_per1{
    color: #fff;
    font-size: 30px;
}
.bargain_per2{
    color: #f9f900;
    font-size: 60px;
    margin-bottom: 15px;
}
.bargain_progress{
    justify-content: center;
    align-items: center;
    height: 80px;
}
.bargain_num{
    flex-direction: row;
    margin-bottom: 10px;
}
.bargain_num1{
    color: #fff;
    margin-right: 60px;
    margin-bottom: 3px;
    background-color: #ff2d2d;
    padding-left: 20px;
    padding-right: 20px;
    padding-top: 5px;
    padding-bottom: 5px;
    border-radius: 20px;
}
.bargain_num2{
    color: #666;
    margin-bottom: 3px;
}
.progress{
    border-style: solid;
    border-width: 1px;
    border-color: #1E90FF;
}
.share{
    align-items: center;
    margin-top: 30px;
    margin-bottom: 30px;
}
.share_text{
    background-color: #1E90FF;
    height: 80px;
    line-height: 80px;
    text-align: center;
    font-size: 36px;
    color: #fff;
    width: 500px;
    border-radius: 10px;
    margin-bottom: 20px;
}
.bargain_list{
    height: 850px;
}
.middle_border{
    height: 10px;
}
.cell_cont{
    padding-left: 5px;
    padding-top: 10px;
    padding-right: 5px;
    background-color: #fff;
}
.bargainlist1{
    flex-direction: row;
    width: 600px;
    justify-content: space-between;
    align-items: center;
}
.bargain_list_content{
    flex-direction: row;
    padding-left: 20px;
    padding-right: 20px;
    height: 80px;
    align-items: center;
    border-top-style: solid;
    border-top-width: 1px;
    border-top-color: #eee;
}
.list_content1{
    color: #666;
    font-size: 30px;
}
.list_content2{
    color: #ff2d2d;
    font-size: 40px;
}
.order_pop{
    position: fixed;
    background-color: #fff;
    height: 800px;
    width: 550px;
    top: 200px;
    left: 100px;
    /* align-items: center; */
}
.order_pop_title{
    height: 100px;
    line-height: 100px;
    font-size: 40px;
    text-align: center;
}
.order_pop_content{
    flex-direction: row;
    height: 80px;
    align-items: center;
}
.order_pop_text1{
    color: #666;
    font-size: 36px;
    width: 300px;
    text-align: right;
}
.order_pop_text2{
    color: #666;
    font-size: 36px;
}
.order_pop_button{
    flex-direction: row;
    height: 130px;
    justify-content: space-around;
    align-items: flex-end;
}
.order_pop_cencel{
    font-size: 40px;
    border-style: solid;
    border-width: 1px;
    border-color: #666;
    border-radius: 8px;
    width: 140px;
    height: 60px;
    line-height: 60px;
    text-align: center;
}
.order_pop_pay{
    font-size: 40px;
    background-color: #1E90FF;
    color: #fff;
    border-radius: 8px;
    width: 140px;
    height: 60px;
    line-height: 60px;
    text-align: center;
}
</style>
